package com.jiuyou.clientController.store;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiuyou.clientController.base.ClientBaseController;
import com.ruoyi.banner.domain.Banner;
import com.ruoyi.banner.service.IBannerService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.PositioningUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.product.domain.StoreProduct;
import com.ruoyi.product.domain.StoreProductJoint;
import com.ruoyi.product.service.IStoreProductJointService;
import com.ruoyi.product.service.IStoreProductService;
import com.ruoyi.searcWord.domain.SearchWord;
import com.ruoyi.searcWord.service.ISearchWordService;
import com.ruoyi.store.domain.Store;
import com.ruoyi.store.service.IStoreService;
import com.ruoyi.storeSource.domain.StoreSource;
import com.ruoyi.storeSource.service.IStoreSourceService;
import com.ruoyi.storeclassify.domain.Storeclassify;
import com.ruoyi.storeclassify.service.IStoreclassifyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.nio.channels.IllegalSelectorException;
import java.util.*;

/**
 * 门店
 *
 * @author jiuyou
 */
@Api(tags = {"C端门店相关"})
@RestController
@RequestMapping("/client/store")
public class StoreClientController extends ClientBaseController
{
    private static final Logger log = LoggerFactory.getLogger(StoreClientController.class);

    @Autowired
    private IStoreService storeService;
    @Autowired
    private IStoreSourceService storeSourceService;
    @Autowired
    private IStoreProductService storeProductService;
    @Autowired
    private IStoreclassifyService storeclassifyService;
    @Autowired
    private ISearchWordService searchWordService;
    @Autowired
    private IStoreProductJointService storeProductJointService;
    @Autowired
    private IBannerService bannerService;
    /**
     * 查询门店列表
     */
  /*  @PreAuthorize("@ss.hasPermi('store:store:list')")
    @GetMapping("/list")
    public TableDataInfo list(Store store)
    {
        startPage();
        List<Store> list = storeService.selectStoreList(store);
        return getDataTable(list);
    }*/

    /**
     * 查询最近的门店 recently
     * */
    @PostMapping("/recentlyStore")
    public AjaxResult list(String latitude, String longitude,Long selectStoreId)
    {
        Store storeParam=new Store();
        storeParam.setLatitude(latitude);
        storeParam.setLongitude(longitude);
        List<Store> list = storeService.selectStoreList(storeParam);
        List<JSONObject> result=new ArrayList<JSONObject>();
        for (Store store:list) {
            JSONObject jso=new JSONObject();
            if(selectStoreId == null){
                jso.put("id",store.getId());
                jso.put("storeName",store.getStoreName());
                jso.put("storeImage",store.getStoreImage());
//            jso.put("storeBacImage",store.getStoreBacImage());
//            jso.put("storePhone",store.getStorePhone());
//            jso.put("addressName",store.getAddressName());
//            jso.put("showState",store.getShowState());
//            jso.put("consumption",store.getConsumption());
//            jso.put("storeLevel",store.getStoreLevel());
                jso.put("location",store.getLocation());
//            jso.put("commentCount",store.getCommentCount());
                jso.put("storeShowImage",store.getStoreShowImage());
            }else{
                Store storeOne = storeService.selectStoreById(selectStoreId);
                jso.put("id",storeOne.getId());
                jso.put("storeName",storeOne.getStoreName());
                jso.put("storeImage",storeOne.getStoreImage());
                jso.put("location",storeOne.getLocation());
                jso.put("storeShowImage",storeOne.getStoreShowImage());
            }
            if(StringUtils.isNotEmpty(longitude)){
                jso.put("range", PositioningUtils.getDistance(Double.parseDouble(latitude),Double.parseDouble(longitude),Double.parseDouble(store.getLatitude()),Double.parseDouble(store.getLongitude())));
            }
            result.add(jso);
        }

        //当前店的推荐商品
        Map<String, Object> params = new HashMap<String, Object>();
        Long storeId = result.get(0).getLong("id");
        params.put("storeId", storeId);
        params.put("state", DicConstants.SYS_Y.getCode());
        List<StoreProduct>  StoreProductJointList = storeProductJointService.selectStoreProductJointByParam(params);
        //System.out.println(StoreProductJointList);
        for (StoreProduct storeProduct : StoreProductJointList) {
            Storeclassify storeclassify = storeclassifyService.selectStoreclassifyById(storeProduct.getClassifyId());
            storeProduct.setClassifyName(storeclassify.getClassifyName());
        }
        result.get(0).put("storeProductJointList",StoreProductJointList);
        //banner展示
        Banner banner = new Banner();
        List<Banner> bannerList = bannerService.selectBannerList(banner);
        result.get(0).put("bannerList",bannerList);

        return AjaxResult.success(result.get(0));
    }


    /**
     * 查询门店列表
     */
    @ApiOperation(value = "查询门店包含商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "当前第几页",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize",value = "每页几条数据",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "storeId",value = "门店id",dataType = "Long"),
            @ApiImplicitParam(name = "searchValue",value = "查询条件,商品名/门店名",required = false,dataType = "String"),
            @ApiImplicitParam(name = "latitude",value = "纬度，经度纬度用来根据定位显示附近商品",required = true,dataType = "String"),
            @ApiImplicitParam(name = "longitude",value = "经度",required = true,dataType = "String"),
    })
    @PostMapping("/list")
    public AjaxResult list(String searchValue, Long classifyId, Long storeId, String latitude, String longitude, Integer pageNum, Integer pageSize,String secondClassifyId,String cityCode)
    {

        Store storeParam=new Store();
        storeParam.getParams().put("searchValue", SqlUtil.participleStr(searchValue));
        if(StringUtils.isNotEmpty(searchValue)){
            SearchWord searchWord = new SearchWord();
            searchWord.setSearchValue(searchValue);
            searchWordService.insertSearchWord(searchWord);
        }
        storeParam.setCityCode(cityCode);
        storeParam.setId(storeId);
        if(null != classifyId && classifyId != 0){
            storeParam.setStoreClassify(classifyId);
        }
        if(StringUtils.isNotEmpty(secondClassifyId)){
            storeParam.setSecondClassify(","+secondClassifyId+",");
        }
        storeParam.setLatitude(latitude);
        storeParam.setLongitude(longitude);
        startPage();
        List<Store> list = storeService.selectStoreList(storeParam);
        TableDataInfo tableDataInfo=getDataTable(list);
        List<JSONObject> result=new ArrayList<JSONObject>();
        for (Store store:list) {
            JSONObject jso=new JSONObject();
            jso.put("id",store.getId());
            jso.put("storeName",store.getStoreName());
            jso.put("storeImage",store.getStoreImage());
            jso.put("storeBacImage",store.getStoreBacImage());
            jso.put("storePhone",store.getStorePhone());
            jso.put("addressName",store.getAddressName());
            jso.put("showState",store.getShowState());
            jso.put("consumption",store.getConsumption());
            jso.put("storeLevel",store.getStoreLevel());
            jso.put("location",store.getLocation());
            jso.put("commentCount",store.getCommentCount());
            if(StringUtils.isNotEmpty(longitude)){
                jso.put("range", PositioningUtils.getDistance(Double.parseDouble(latitude),Double.parseDouble(longitude),Double.parseDouble(store.getLatitude()),Double.parseDouble(store.getLongitude())));
            }

            StoreProduct storeProductParam=new StoreProduct();
            storeProductParam.setStoreId(store.getId());
            storeProductParam.setState(DicConstants.SYS_Y.getCode());
            if(null != classifyId && classifyId != 0){
                storeProductParam.setClassifyParentId(classifyId);
            }
            storeProductParam.getParams().put("searchValue",SqlUtil.participleStr(searchValue));

            startPage(1,2,null,false);
            List<StoreProduct> proList= storeProductService.selectStoreProductList(storeProductParam);
            JSONArray proArry=new JSONArray();
            for (StoreProduct storeProduct:proList ) {
                JSONObject proJso=new JSONObject();
                proJso.put("productName",storeProduct.getProductName());
                proJso.put("classifyName",storeclassifyService.selectStoreclassifyById(storeProduct.getClassifyId()).getClassifyName());
                proJso.put("salesNum",storeProduct.getSalesNumShow());
                proJso.put("price",storeProduct.getPrice());
                proJso.put("storePrice",storeProduct.getStorePrice());
                proJso.put("couponsMaxNewUse",storeProduct.getCouponsMaxNewUse());
                proArry.add(proJso);
            }
            jso.put("products",proArry);
            result.add(jso);
        }
        tableDataInfo.setRows(result);
        return AjaxResult.success(tableDataInfo);
    }

    public static void main(String[] args) {
//      String str=  participleStr("剪发烫发");
//     System.out.println(str);
    }


    /**
     * 获取门店详细信息
     */
    @ApiOperation(value = "获取门店详情")
    @ApiImplicitParam(name = "id",value = "门店id",dataType = "Long")
    @PostMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        Store store=storeService.selectStoreById(id);
        if(null==store){
            return AjaxResult.error("参数错误");
        }
        JSONObject result=new JSONObject();
        result.put("id",store.getId());
        result.put("storeImage",store.getStoreImage());
        result.put("storeBacImage",store.getStoreBacImage());
        result.put("storeName",store.getStoreName());
        result.put("storePhone",store.getStorePhone());
        result.put("addressName",store.getAddressName());
        result.put("brandDetail",store.getBrandDetail());
        result.put("showState",store.getShowState());
        result.put("storeState",store.getStoreState());
        result.put("consumption",store.getConsumption());
        result.put("serviceItem",store.getServiceItem());
        result.put("businessStart",store.getBusinessStart());
        result.put("businessEnd",store.getBusinessEnd());
        result.put("storeLevel",store.getStoreLevel());
        result.put("effectLevel",store.getEffectLevel());
        result.put("environmentLevel",store.getEnvironmentLevel());
        result.put("serviceLevel",store.getServiceLevel());
        result.put("location",store.getLocation());
        result.put("longitude",store.getLongitude());
        result.put("latitude",store.getLatitude());
        result.put("storePhone",store.getStorePhone());
        return AjaxResult.success(result);
    }
    @ApiOperation(value = "查询门店图册列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "当前第几页",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize",value = "每页几条数据",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "storeId",value = "门店id",required = true,dataType = "Long"),
            @ApiImplicitParam(name = "groupType",value = "资源类型参照当前门店类型接口返回的数据",required = true,dataType = "String"),
            @ApiImplicitParam(name = "sourceType",value = "图片或者视频图片传img 视频传video",dataType = "String"),
    })
    @PostMapping("/listStoreSource")
    public AjaxResult listStoreSource(Long storeId,String sourceType,String groupType,Integer pageNum,Integer pageSize)
    {
        StoreSource storeSourceParam=new StoreSource();
        storeSourceParam.setStoreId(storeId);
        storeSourceParam.setSourceType(sourceType);
        storeSourceParam.setGroupType(groupType);
        startPage();
        List<StoreSource> list = storeSourceService.selectStoreSourceList(storeSourceParam);
        TableDataInfo tableDataInfo=getDataTable(list);
       List<JSONObject> jsoList=new ArrayList<JSONObject>();
        for (StoreSource storeSource:list) {
            JSONObject jso=new JSONObject();
            jso.put("sourceType",storeSource.getSourceType());
            jso.put("groupType",storeSource.getGroupType());
            jso.put("url",storeSource.getUrl());
            jso.put("video",storeSource.getVideo());
            jsoList.add(jso);
        }
        tableDataInfo.setRows(jsoList);
        return AjaxResult.success(tableDataInfo);
    }

    @ApiOperation(value = "查询门店图册资源类型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId",value = "门店id",required = true,dataType = "Long"),
    })
    @PostMapping("/listStoreSourceGroupType")
    public AjaxResult listStoreSourceGroupType(Long storeId)
    {
        List<String> list = storeSourceService.listStoreSourceGroupType(storeId);
        JSONArray result=new JSONArray();
        for (String str:list) {
            JSONObject jso=new JSONObject();
            jso.put(str, DictUtils.getDictLabel("store_group_type",str));
            result.add(jso);
        }
        return AjaxResult.success(result);
    }

}
